import { defineStore } from 'pinia'
import { storage } from '../utils/storage'
import { getRouters } from '../api/auth/menu'
import router from '../router'

const navConfig = [
    {
        key: 'media',
        title: '新媒体',
        pathPrefix: '/media',
        secondLevel: {
            setter: 'setActiveSecondNav',
            defaultPath: '/media/text-gen'
        }
    },
    {
        key: 'consulting',
        title: '顾问部',
        pathPrefix: '/consulting',
        secondLevel: {
            setter: 'setActiveThirdNav',
            defaultPath: '/consulting/customer'
        }
    },
    {
        key: 'xueguan',
        title: '学管部',
        pathPrefix: '/xueguan',
        secondLevel: {
            setter: 'setActiveFourthNav',
            defaultPath: '/xueguan/class'
        }
    },
    {
        key: 'jiaoxue',
        title: '教学部',
        pathPrefix: '/jiaoxue',
        secondLevel: {
            setter: 'setActiveFifthNav',
            defaultPath: '/jiaoxue/class'
        }
    },
    {
        key: 'profile',
        title: '账号信息',
        pathPrefix: '/profile',
        secondLevel: {
            setter: 'setActiveSixthNav',
            defaultPath: '/profile/account'
        }
    },
]

export const useSidebarStore = defineStore('sidebar', {
    state: () => ({
        menuData: [],
        menuLoading: false,
        menuError: null,

        activeNav: 0,
        activeSecondNav: 0,
        activeThirdNav: 0,
        activeFourthNav: 0,
        activeFifthNav: 0,
        activeSixthNav: 0,
        generationType: 0,

        lastPaths: navConfig.reduce((acc, item) => {
            acc[item.key] = item.secondLevel.defaultPath
            return acc
        }, {}),
        initialized: false
    }),
    getters: {
        availableNavConfigs() {
            if (this.menuError) {
                return navConfig
                    .map((config, index) => ({ ...config, activeNavIndex: index }))
            }
            return navConfig
                .filter(config => this.menuData.some(menu => menu.name === config.title))
                .map((config, index) => ({ ...config, activeNavIndex: index }))
        },

        getActiveSubNavIndex: (state) => (moduleKey) => {
            const indexMap = {
                media: state.activeSecondNav,
                consulting: state.activeThirdNav,
                xueguan: state.activeFourthNav,
                jiaoxue: state.activeFifthNav,
                profile: state.activeSixthNav
            }
            return indexMap[moduleKey] || 0
        },

        getParentRoute: () => (currentPath, moduleConfig) => {
            if (!currentPath || !moduleConfig?.pathPrefix) {
                return moduleConfig?.secondLevel.defaultPath || '/'
            }

            const matchedRoute = router.getRoutes().find(route =>
                currentPath.startsWith(route.path) && route.path !== '/'
            )
            if (matchedRoute?.meta?.parentRoute) {
                return matchedRoute.meta.parentRoute
            }

            const modulePrefix = moduleConfig.pathPrefix
            const subRoutes = router.getRoutes()
                .filter(r =>
                    r.path.startsWith(modulePrefix) &&
                    r.path !== modulePrefix &&
                    !!r.path
                )
                .map(r => r.path)

            const matchedSubRoute = subRoutes
                .filter(route => currentPath.startsWith(route))
                .sort((a, b) => b.length - a.length)[0]

            return matchedSubRoute || moduleConfig.secondLevel.defaultPath
        }
    },
    actions: {
        async fetchMenuData() {
            this.menuLoading = true
            this.menuError = null
            this.menuData = []

            try {
                const response = await getRouters()
                if (!response || !Array.isArray(response.data)) {
                    throw new Error('接口返回格式不正确')
                }

                this.menuData = response.data
                    .map(item => ({
                        name: item.meta?.title || '',
                        icon: item.meta?.icon || '',
                        path: item.path || ''
                    }))
                    .filter(item => item.path && item.name)

                if (this.menuData.length === 0) {
                    throw new Error('未获取到有效菜单数据')
                }

                this.initializeNavState(true)
            } catch (err) {
                console.error('获取菜单失败:', err)
                this.menuError = err.message || '菜单加载失败'
                this.initializeNavState(true)
            } finally {
                this.menuLoading = false
            }
        },

        initializeNavState(isFirstLoad = false) {
            const availableConfigs = this.availableNavConfigs;
            if (availableConfigs.length === 0) {
                availableConfigs.push({
                    ...navConfig[0],
                    activeNavIndex: 0
                });
            }

            const targetConfig = availableConfigs.find(config =>
                this.menuData.some(menu => menu.name === config.title)
            );
            if (targetConfig) {
                this.setActiveNav(targetConfig.activeNavIndex);
                this[targetConfig.secondLevel.setter](0, targetConfig.secondLevel.defaultPath);
                if (targetConfig.key === 'media') this.setGenerationType(0);
            }
        },

        getDefaultRoute() {
            const availableConfigs = this.availableNavConfigs
            const targetConfig = availableConfigs[0]
            return targetConfig ? targetConfig.secondLevel.defaultPath : '/'
        },

        setActiveNav(index) {
            this.activeNav = index
            this.persistState()
        },

        setActiveSecondNav(index, path) {
            this.activeSecondNav = index
            if (path) this.lastPaths.media = path
            this.persistState()
        },

        setActiveThirdNav(index, path) {
            this.activeThirdNav = index
            if (path) this.lastPaths.consulting = path
            this.persistState()
        },

        setActiveFourthNav(index, path) {
            this.activeFourthNav = index
            if (path) this.lastPaths.xueguan = path
            this.persistState()
        },

        setActiveFifthNav(index, path) {
            this.activeFifthNav = index
            if (path) this.lastPaths.jiaoxue = path
            this.persistState()
        },

        setActiveSixthNav(index, path) {
            this.activeSixthNav = index
            if (path) this.lastPaths.profile = path
            this.persistState()
        },

        setGenerationType(type) {
            this.generationType = type
            this.persistState()
        },

        syncStateFromPath(currentPath) {
            const availableConfigs = this.availableNavConfigs;
            const matchedConfig = availableConfigs.find(config =>
                currentPath.startsWith(config.pathPrefix)
            );

            if (matchedConfig) {
                this.setActiveNav(matchedConfig.activeNavIndex);
                const parentRoute = this.getParentRoute(currentPath, matchedConfig);
                this.handleSubPathMatch(parentRoute, matchedConfig);
            } else {
                const targetConfig = availableConfigs.find(config =>
                    this.menuData.some(menu => menu.name === config.title)
                );
                if (targetConfig) {
                    this.setActiveNav(targetConfig.activeNavIndex);
                    this[targetConfig.secondLevel.setter](0, targetConfig.secondLevel.defaultPath);
                }
            }
        },

        handleSubPathMatch(path, config) {
            switch (config.key) {
                case 'media':
                    if (path.includes('/text-gen')) {
                        this.setActiveSecondNav(0, path); this.setGenerationType(0)
                    } else if (path.includes('/image-gen')) {
                        this.setActiveSecondNav(0, path); this.setGenerationType(1)
                    } else if (path.includes('/copy-opt')) {
                        this.setActiveSecondNav(0, path); this.setGenerationType(2)
                    } else if (path.includes('/note')) {
                        this.setActiveSecondNav(1, path)
                    } else if (path.includes('/stats')) {
                        this.setActiveSecondNav(2, path)
                    } else {
                        this.setActiveSecondNav(0, config.secondLevel.defaultPath); this.setGenerationType(0)
                    }
                    break
                case 'consulting':
                    if (path.includes('/customer')) this.setActiveThirdNav(0, path)
                    else if (path.includes('/note-code')) this.setActiveThirdNav(1, path)
                    else if (path.includes('/class')) this.setActiveThirdNav(2, path)
                    else this.setActiveThirdNav(0, config.secondLevel.defaultPath)
                    break
                case 'xueguan':
                    if (path.includes('/class')) this.setActiveFourthNav(0, path)
                    else this.setActiveFourthNav(0, config.secondLevel.defaultPath)
                    break
                case 'jiaoxue':
                    if (path.includes('/class')) this.setActiveFifthNav(0, path)
                    else this.setActiveFifthNav(0, config.secondLevel.defaultPath)
                    break
                case 'profile':
                    if (path.includes('/account')) this.setActiveSixthNav(0, path)
                    else if (path.includes('/password')) this.setActiveSixthNav(1, path)
                    else this.setActiveSixthNav(0, config.secondLevel.defaultPath)
                    break
            }
        },

        persistState() {
            storage.set('sidebarState', this.$state)
        },

        restoreState() {
            try {
                const saved = storage.get('sidebarState')
                if (saved) {
                    this.$patch(saved)
                }
            } catch (err) {
                console.error('恢复状态失败:', err)
                storage.remove('sidebarState')
            } finally {
                this.initializeNavState()
            }
        }
    }
})
